import { getUserInfo, login, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
const state = {
  token: localStorage.getItem('token') || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    // 存到本地储存, 避免刷新丢失
    localStorage.setItem('token', data)
    // 存到 state 马上使用
    state.token = data
  },
  setUserInfo(state, data) {
    state.userInfo = { ...data }
  },
  removeToken(state) {
    state.token = ''
    localStorage.removeItem('token')
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async login(store, data) {
    const res = await login(data)
    // store.commit('setToken', res.data.data)
    store.commit('setToken', res)
    // console.log(res)
    // 记录登录时间, 方便主动检查超时
    localStorage.setItem('loginTime', Date.now())
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    // 这里数据不够, 再发一个请求拿更多数据
    const detail = await getUserDetailById(res.userId)
    store.commit('setUserInfo', {
      ...res,
      ...detail
    })
  },
  logout(store) {
    resetRouter()
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
